import axios from "axios";
import qs from "qs";
import { Message } from 'element-ui';
import router from '@/router';

// create an axios instance
const service = axios.create({
  baseURL: "https://api.xujiangyu.com/admin", // 测试服
  // baseURL: "https://wudao.topshow.cc",//正式服
  //   withCredentials: true, //send cookies when cross-domain requests
  headers: {
    "Content-Type": "application/x-www-form-urlencoded"
    // 'Content-Type': 'application/json; charset=utf-8'
  },
  timeout: 5000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.data = qs.stringify(config.data);
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // console.log(response);
    const res = response.data;
    if (res.code == 10000) {
      // console.log(res)
      return res;
    }else if(res.code == 10002){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
      localStorage.clear();
      if(router.history.current.path != '/'){
        router.replace('/');
      }
    }else if(res.code == 10001){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else if(res.code == 10003){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else if(res.code == 10004){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else if(res.code == 20001){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else if(res.code == 20002){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else if(res.code == 30001){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else if(res.code == 2000){
      Message({
        message: res.message,
        type: 'error',
        duration:1500
      });
    }else{
      return res;
    }
  },
  error => {
    console.log("err" + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
